package com.leetcode;



/**
 * 反转链表
 *
 * @author winson
 * @create 2022-04-12 10:26
 */
public class ReverseListSolution {

    public ListNode reverseList(ListNode head) {
        if (head == null) {
            return null;
        }
        ListNode ans = null;
        ListNode current = head;
        ListNode next = null;
        while (current != null) {
            next = current.next;
            current.next = ans;
            ans = current;
            current = next;
        }
        return ans;
    }

    public ListNode recursion(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode ans = recursion(head.next);
        head.next.next = head;
        head.next = null;
        return ans;
    }

    public static void main(String[] args) {
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(5);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
        ReverseListSolution solution = new ReverseListSolution();
        ListNode ans = solution.reverseList(node1);
        System.out.println(ans);
        ListNode listNode = solution.recursion(ans);
        System.out.println(listNode);
    }
}
